<template>
  <div class="app-container" id="uploadimage" ref="uploadingImg">
    <el-row :gutter="10" class="mb8">
      <el-col :span="16" style="display: flex; align-items: flex-start">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
        >
          <el-form-item label-width="100px" prop="totalOrder">
            <span slot="label">
              <el-tooltip
                content="综合查询包含物料代码、物料品名和物料规格"
                placement="top"
              >
                <i class="el-icon-question"></i>
              </el-tooltip>
              综合查询
            </span>
            <el-input
              v-model="queryParams.totalOrder"
              placeholder="请输入物料代码或品名规格或客户编码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:iqmMstr:add']"
          >新增</el-button
        >
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['project:iqmMstr:edit']"
        >
          修改
        </el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['project:iqmMstr:remove']"
        >
          删除
        </el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['project:iqmMstr:export']"
        >
          导出
        </el-button>
      </el-col>
      <el-col :span="8" style="text-align: right">
        <Page
          style="margin-right: 0px"
          :current="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :total="total"
          @on-change="pageChange"
          simple
        ></Page>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="iqmMstrList"
      stripe
      border
      highlight-current-row
      ref="multipleTable"
      @selection-change="handleSelectionChange"
      @row-click="clickRow"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column label="物料代码" align="center" prop="itmWldm" />
      <el-table-column label="品名" align="center" prop="itmWlpm" />
      <el-table-column label="物料规格" align="center" prop="itmWlgg" />
      <el-table-column label="单位" align="center" prop="itmDw">
        <template #default="scope">
          <dict-tag :options="dwOptions" :value="scope.row.itmDw" />
        </template>
      </el-table-column>
      <el-table-column label="最小包装" align="center" prop="itmMinbz" />
      <el-table-column label="参考单价" align="center" prop="itmPrice" />
      <el-table-column label="建立人员" align="center" prop="createBy" />
      <el-table-column label="建立日期" align="center" prop="createTime">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更改人员" align="center" prop="updateBy" />
      <el-table-column label="更改日期" align="center" prop="updateTime">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.updateTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:iqmMstr:edit']"
          >
            修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:iqmMstr:remove']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="图片"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleImg(scope.row)"
            v-hasPermi="['project:iqmMstr:edit']"
          >
            图片上传
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--物料图片对话框-->
    <el-dialog
      :title="title"
      v-model="openImg"
      :close-on-click-modal="false"
      draggable
      width="500px"
      append-to-body
      :show-close="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物料代码" prop="itmWldm">
          <el-input v-model="form.itmWldm" disabled />
        </el-form-item>
        <el-form-item label="品名" prop="itmWlpm">
          <el-input v-model="form.itmWlpm" disabled />
        </el-form-item>
      </el-form>
      <div style="margin-top: 50px; width: 100%; text-align: right">
        <el-upload
          action="#"
          :http-request="requestUpload"
          :show-file-list="false"
          :before-upload="beforeUpload"
        >
          <el-button size="small">
            上传
            <i class="el-icon-upload el-icon--right"></i>
          </el-button>
        </el-upload>
      </div>
    </el-dialog>
    <!-- 添加或修改非生产物料信息对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      :close-on-click-modal="false"
      draggable
      width="750px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-col :span="12">
          <el-form-item label="物料代码">
            <el-input placeholder="流水号生成" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="品名" prop="itmWlpm">
            <el-input
              @input="searchIqm"
              v-model="form.itmWlpm"
              placeholder="请输入品名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="物料规格" prop="itmWlgg">
            <el-input v-model="form.itmWlgg" placeholder="请输入物料规格" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单位" prop="itmDw">
            <el-select
              v-model="form.itmDw"
              placeholder="请选择单位"
              :disabled="title.indexOf('修改') !== -1"
            >
              <el-option
                v-for="dict in dwOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="最小包装" prop="itmMinbz">
            <el-input v-model="form.itmMinbz" placeholder="请输入最小包装" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="参考单价" prop="itmPrice">
            <el-input v-model="form.itmPrice" placeholder="请输入参考单价" />
          </el-form-item>
        </el-col>
      </el-form>

      <div v-if="title === '非生产物料信息录入'">
        <el-table v-loading="loading" :data="iqmSearchList" height="400px">
          <el-table-column type="selection" width="65" align="center" />
          <el-table-column
            label="物料代码"
            width="150"
            align="center"
            prop="itmWldm"
          />
          <el-table-column label="品名" align="center" prop="itmWlpm" />
          <el-table-column label="物料规格" align="center" prop="itmWlgg" />
          <el-table-column label="单位" align="center" prop="itmDw">
            <template #default="scope">
              <dict-tag :options="dwOptions" :value="scope.row.itmDw" />
            </template>
          </el-table-column>
        </el-table>
        <Page
          style="text-align: right; width: 100%"
          :current="queryParams2.pageNum"
          :page-size="queryParams2.pageSize"
          :total="totalSearch"
          @on-change="searchIqm"
          simple
        ></Page>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <div class="imgSr">
      <img ref="imgSrc" :src="userImg" alt="" />
    </div>
  </div>
</template>

<script>
import {
  listIqmMstr,
  getIqmMstr,
  delIqmMstr,
  addIqmMstr,
  updateIqmMstr,
  exportIqmMstr,
  getIqmMstrByPm,
  uploadImg,
  getIqmByPmgg,
} from "@/api/project/iqmMstr";
import { getUserProfile } from "@/api/system/user";

export default {
  name: "IqmMstr",
  data() {
    return {
      use: "",
      userImg: null,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 非生产物料信息表格数据
      iqmMstrList: [],
      //1.搜索出来的非生产信息表格数据
      iqmSearchList: [],

      totalSearch: 0,
      // 弹出层标题
      title: "",
      //重新加载
      timer: "",
      wldm: "",
      // 是否显示弹出层
      open: false,
      //物料图片弹窗
      openImg: false,
      // 单位字典
      dwOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        totalOrder: null,
        itmType: "Q",
      },
      queryParams2: {
        pageNum: 1,
        pageSize: 20,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        itmWlpm: [{ required: true, message: "品名不能为空", trigger: "blur" }],
        itmWlgg: [
          { required: true, message: "物料规格不能为空", trigger: "blur" },
        ],
        itmDw: [{ required: true, message: "单位不能为空", trigger: "change" }],
        itmMinbz: [
          { required: true, message: "最小包装不能为空", trigger: "blur" },
        ],
        itmPrice: [
          { required: true, message: "参考单价不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_unit").then((response) => {
      this.dwOptions = response.data;
    });

    this.getUser();
    // this.clickRow();
  },
  methods: {
    requestUpload() {},
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          let formData = new FormData();
          formData.append("avatarfile", file);
          formData.append("wldm", this.form.itmWldm);
          uploadImg(formData).then((response) => {
            this.openImg = false;
            this.msgSuccess("修改成功");
            document.body.clientHeight;
            this.userImg = reader.result;
            this.getList(this.userImg);
          });
        };
      }
    },
    clickRow(a) {
      //点击行触发，选中或不选中复选框
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(a);
      this.timer = new Date().getTime();
      this.userImg = a.itmImage
        ? process.env.VUE_APP_BASE_API + a.itmImage
        : null;
    },
    getUser() {
      getUserProfile().then((response) => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    /** 查询非生产物料信息列表 */
    getList(row) {
      this.loading = true;
      listIqmMstr(this.queryParams).then((response) => {
        this.iqmMstrList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.childBomList = [];
        if (row != null) {
        } else if (this.iqmMstrList != null && this.iqmMstrList.length > 0) {
          this.userImg =
            process.env.VUE_APP_BASE_API + this.iqmMstrList[0].itmImage;
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelImg() {
      this.openImg = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        itmId: null,
        itmWldm: null,
        itmWlpm: null,
        itmWlgg: null,
        itmDw: null,
        itmMinbz: null,
        itmImage: null,
        itmPrice: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.itmId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "非生产物料信息录入";
      this.iqmSearchList = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const itmId = row.itmId || this.ids;
      getIqmMstr(itmId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改非生产物料信息";
      });
    },
    /** 物料图片信息 */
    handleImg(row) {
      this.reset();
      const itmId = row.itmId || this.ids;
      getIqmMstr(itmId).then((response) => {
        this.form = response.data;
        this.openImg = true;
        this.title = "物料图片上传";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.itmWlgg.indexOf("如图") > -1) {
            this.msgError(
              "建立非生产物料信息不准再用“如图”做为规格，这样会影响财务部对采购单价的核定!"
            );
            return;
          }
          if (this.form.itmId != null) {
            updateIqmMstr(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if (this.isEmpty(this.iqmSearchList)) {
              this.msgError("存在相似的非生产物料,请核对,添加失败~");
              return;
            } else {
              addIqmMstr(this.form).then((response) => {
                this.msgSuccess("新增成功");
                this.getList();
                this.open = false;
                const query = {
                  pageNum: 1,
                  pageSize: 25,
                  itmWlpm: this.form.itmWlpm,
                  itmWlgg: this.form.itmWlgg,
                };
                this.form = [];
                listIqmMstr(query).then((res) => {
                  if (res.rows.length > 0) {
                    this.form = res.rows[0];
                    this.openImg = true;
                    this.title = "物料图片上传";
                  }
                });
              });
            }
          }
        }
      });
    },
    isEmpty(iqmSearchList) {
      //判断如果存在相似物料,不允许新增
      if (iqmSearchList.length > 0) {
        for (let i of iqmSearchList) {
          if (
            i.itmWlpm === this.form.itmWlpm &&
            i.itmWlgg === this.form.itmWlgg
          )
            return true;
        }
      }
      return false;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const itmIds = row.itmId || this.ids;
      this.$confirm("是否确认删除选中的数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delIqmMstr(itmIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    pageChange(page) {
      this.queryParams.pageNum = page;
      this.getList();
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有非生产物料信息数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportIqmMstr(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    //2.根据监听input输入的内容匹配
    searchIqm() {
      if (this.title !== "非生产物料信息录入") {
        return;
      }
      //获取输入框里面的内容
      this.queryParams2.itmWlpm = this.form.itmWlpm;
      this.loading = true;
      this.iqmSearchList = [];
      getIqmMstrByPm(this.queryParams2).then((response) => {
        this.iqmSearchList = response.rows;
        this.totalSearch = response.total;
        this.loading = false;
      });
    },
  },
};
</script>
<style scoped lang="scss">
.imgSr {
  /*display: none;*/
  img {
    height: 300px;
    object-fit: cover;
  }
}
</style>
